package com.gtone.usbtool.encrypt;

import android.util.Log;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

    private static final String ALGORITHM = "AES";

    public static final String KEY = "366242f9b1a1445156c6129a69929965";

    /**
     * 生成密钥
     */
    public static String initAesKey(String seed) throws NoSuchAlgorithmException, Exception {
        SecureRandom secureRandom;
        if (StringUtil.isNotBlankAndEmpty(seed)) {
            secureRandom = new SecureRandom(HexUtils.decodeHex(seed));
//            secureRandom = new SecureRandom(Hex.stringToBytes(seed));
        } else {
            secureRandom = new SecureRandom();
        }
        // init key生成器
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        // 要生成多少位，只需要修改这里即可 128, 192 或 256，单位 bit
        kg.init(128, secureRandom);
        // 生成一个Key
        SecretKey secretKey = kg.generateKey();
        // 转变为字节数组
        byte[] encoded = secretKey.getEncoded();
        // 生成密钥字符串
        return HexUtils.encodeHexString(encoded);
//        return Hex.bytesToStringLowercase(encoded);
    }

    /**
     * AES加密
     *
     * @param data 待加密的数据
     * @param key  密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data, String key) {
        try {
            Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
            return HexUtils.encodeHexString(cipher.doFinal(data.getBytes())).toUpperCase();
//            return Hex.bytesToStringLowercase(cipher.doFinal(data.getBytes())).toUpperCase();
        } catch (Exception e) {
            Log.e("AESUtils", "加密异常e===" + e + "");
            return null;
        }
    }


    /**
     * AES解密
     *
     * @param data 待解密的数据
     * @param key  密钥
     * @return 解密后的数据
     */
    public static String decrypt(String data, String key) {
        try {
            Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
            return new String(cipher.doFinal(HexUtils.decodeHex(data)));
//            return new String(cipher.doFinal(Hex.stringToBytes(data)));
        } catch (Exception e) {
            Log.e("AESUtils", "解密异常e===" + e + "");
            return null;
        }
    }

    private static Cipher getCipher(String key, Integer mode) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, Exception {
        // 创建密匙
        SecretKey secretKey = new SecretKeySpec(HexUtils.decodeHex(key), ALGORITHM);
//        SecretKey secretKey = new SecretKeySpec(Hex.stringToBytes(key), ALGORITHM);
        // Cipher 对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        // 用密匙初始化 Cipher 对象
        cipher.init(mode, secretKey);
        return cipher;
    }

    public static String generateKey(String data) {
        int hashCode = data.hashCode();
        try {
            int abs = Math.abs(hashCode % 1024);
            return initAesKey(abs + "" + abs);
        } catch (Exception e) {
            Log.e("AESUtils", "generateKey加密异常e===" + e + "");
            try {
                return initAesKey("1024");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return KEY;
    }

    public static void main(String[] args) throws Exception {
        String bjdj = generateKey("1234");
        System.out.println(bjdj);
    }

}
